package com.yusong.algorithm.array;

import java.util.LinkedList;
import java.util.List;

public class Decode394 {

    public static void main(String[] args) {

        Decode394 main = new Decode394();
        String s = "";
        List list = new LinkedList();

        String res = main.decodeString("3[a2[c]]");

        System.out.println(res);

    }

    private final static String LEFT = "[";
    private final static String RIGHT = "]";

    //全局变量
    int index;
    /**
     消防逆波兰表达式解法
     数字进数字栈
     子母进子母栈，右括号出栈，出到第一个左括号为止
     **/
    public String decodeString(String s) {
        char[] ss = s.toCharArray();
        int length = s.length();
        index = 0;
        StringBuffer sb = new StringBuffer();
        //数字其实是操作符
        LinkedList<Integer> numberStack = new LinkedList<>();
        LinkedList<String> dataStack = new LinkedList<>();
        while(index < length){
            int number = beNumber(ss);
            if(number > 0){
                numberStack.add(number);
                continue;
            }
            String str = ""+ ss[index];
            if(RIGHT.equals(str)){
                //出栈到LEFT
                String subStr = "";
                String preStr = "";
                while(!LEFT.equals(preStr) && dataStack.size() > 0){
                    preStr = dataStack.removeLast();
                    subStr = preStr + subStr;
                }
                //取数字
                Integer times = null;
                if(numberStack.size() > 0){
                    times = numberStack.removeLast();
                }

                if(null == times){
                    dataStack.add(subStr);
                }else{
                    String data = "";
                    for(int i = 0; i <times ;i++ ){
                        data = data + subStr;
                    }
                    dataStack.add(data);
                }
                index++;
            }else{
                dataStack.add(str);
                index++;
            }
        }

        for(String str: dataStack){
            sb.append(str);
        }
        return sb.toString();
    }


    /**
     *判断当前Index是否是数字
     * 大于10的整数
     **/
    private Integer beNumber(char[] ss){
        char firstC = ss[index];
        if(!Character.isDigit(firstC)){
            return -1;
        }
        StringBuffer sb = new StringBuffer();
        int i = index;
        for(; i< ss.length; i++){
            char c = ss[i];
            if(Character.isDigit(c)){
                sb.append(c);
            }else {
                break;
            }
        }
        index = i ;
        return Integer.parseInt(sb.toString());
    }
}
